<template>
  <div
    class="chart"
    :id="'echart' + props.id"
    ref="chart"
    :style="{ width: props.width + 'px', height: props.height + 'px' }"
  ></div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts'

defineOptions({ name: 'EchartsGlobal' })
let chart = ref<any>(null)
let myChart = null as any
let props = defineProps({
  // 传配置项option
  option: {
    type: Object,
    default() {
      return {}
    },
  },
  width: {
    type: [Number, String],
    default: 300,
  },
  height: {
    type: [Number, String],
    default: 300,
  },
  id: {
    default: '',
  },
})
let emits = defineEmits(['echart_callback'])

watch(
  props.option,
  (newVal) => {
    if (chart.value) {
      chart.value.setOption(newVal)
    }
  },
  { deep: true },
)

onMounted(() => {
  if (props.id != '') {
    myChart = echarts.init(document.getElementById('echart' + props.id))
  } else {
    myChart = echarts.init(chart.value)
  }

  myChart.setOption(props.option, true)

  function echart_callbackFun() {
    emits('echart_callback', myChart)
  }
  echart_callbackFun()

  window.addEventListener('resize', function () {
    myChart.resize()
  })
})
</script>

<style scoped lang="scss"></style>
